package P5;

public class P5_longestPalindrome {
    public static void main(String[] args) throws Exception {

        System.out.println(new P5_longestPalindrome().longestPalindrome("aacabdkacaa"));
    }

    public String longestPalindrome(String s) {
        if (s.length() <= 1) {
            return s;
        }

        //长度最小时候为1，首字母就可以
        int maxLength = 1;
        int maxIndex = 0;

        int length = s.length();
        boolean[][] dp = new boolean[length][length];

        //初始化
        for (int i = 0; i < length; i++) {
            dp[i][i] = true;
        }
        for (int i = 0; i < length - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                dp[i][i + 1] = true;
                if (2 > maxIndex) {
                    maxLength = 2;
                    maxIndex = i;
                }
            }
        }

        //循环长度，长度为1 和 2 的已经初始化了
        for (int len = 3; len <= s.length(); len++) {
            //循环起点
            for (int i = 0; i < s.length(); i++) {
                int j = i + len - 1;
                if (j >= s.length()) {
                    break;
                }

                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i + 1][j - 1];

                    if (dp[i][j] && len > maxLength) {
                        maxLength = len;
                        maxIndex = i;
                    }

                } else {
                    dp[i][j] = false;
                }

            }
        }

        return s.substring(maxIndex, maxIndex + maxLength);
    }

}
